using System.Drawing;
using GTA;
using NativeUI;

namespace CustomPeds.Menus;

public class SpeechMenu : Script
{
    public static UIMenu menu = new UIMenu("", TextSetting.Speech_Menu, new Point(0, -107));
    private static bool isMenuInitialized;

    private static string[] VoiceName;

    private static string DefaultVoice;

    private static Origin origin;

    public SpeechMenu()
    {
        if (!isMenuInitialized)
        {
            Main.pool.Add(menu);
            menu.OnItemSelect += OnItemSelect;
            menu.OnMenuClose += OnMenuClose;
            isMenuInitialized = true;
        }
    }

    public static void InitSpeakMenu()
    {
        origin = (DressingScript.Dressing == Main.Member.P1) ? Main.P1 : Main.P2;
        DefaultVoice = origin.skin.Voice;
        menu.Clear();
        SetGenderVoiceArray();
        menu.SetBannerType(new UIResRectangle());
        int currentSelection = 0;
        for (int i = 0; i < VoiceName.Length; i++)
        {
            if (VoiceName[i] == DefaultVoice)
            {
                menu.AddItem(new UIMenuItem("~y~" + VoiceName[i]));
                currentSelection = i;
            }
            else
            {
                menu.AddItem(new UIMenuItem(VoiceName[i]));
            }
        }
        menu.CurrentSelection = currentSelection;
        menu.Visible = true;
        menu.RefreshIndex();
    }

    private void OnItemSelect(UIMenu sender, UIMenuItem item, int index)
    {
        DefaultVoice = menu.MenuItems[index].Text.Replace("~y~", "");
        if (DressingScript.Dressing == Main.Member.P1)
        {
            origin.skin.Voice = (Main.Clone.skin.Voice = DefaultVoice);
            origin.Character.SetVoice(DefaultVoice);
            Main.Clone.Character.SetVoice(DefaultVoice);
            Main.Clone.Character.PlayAmbientSpeech1("CHAT_STATE", immediately: true);
        }
        else
        {
            origin.skin.Voice = DefaultVoice;
            origin.Character.SetVoice(DefaultVoice);
            origin.Character.PlayAmbientSpeech1("CHAT_STATE", immediately: true);
        }
        menu.MenuItems[index].Text = "~y~" + menu.MenuItems[index].Text;
        InitSpeakMenu();
    }

    private static void SetGenderVoiceArray()
    {
        VoiceName = (origin.Character.Gender == Gender.Male) ? Skin.MALE_VOICE_NAME : Skin.FEMALE_VOICE_NAME;
    }

    private void OnMenuClose(UIMenu sender)
    {
        // 最小化关闭：不做回写，不刷新
        menu.Visible = false;
    }
}


